package org.itheima.service.impl;

import org.itheima.mapper.WarehouseMapper;
import org.itheima.service.CompareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CompareServiceImpl implements CompareService {


    @Override
    public double computeCosineSimilarity(String text1, String text2) {

        // 分词
        List<String> words1 = Arrays.asList(text1.toLowerCase().split("\\s+"));
        List<String> words2 = Arrays.asList(text2.toLowerCase().split("\\s+"));
        System.out.println("word1:"+words1);
        System.out.println("word2:"+words2);
        // 统计词频
        Map<String, Integer> freq1 = words1.stream().collect(Collectors.toMap(w -> w, w -> 1, Integer::sum));
        Map<String, Integer> freq2 = words2.stream().collect(Collectors.toMap(w -> w, w -> 1, Integer::sum));
        System.out.println("词频1:"+freq1);
        System.out.println("词频2:"+freq2);
        // 计算余弦相似度
        Set<String> allWords = new HashSet<>(freq1.keySet());
        allWords.addAll(freq2.keySet());

        double dotProduct = 0, norm1 = 0, norm2 = 0;
        for (String word : allWords) {
            int v1 = freq1.getOrDefault(word, 0);
            int v2 = freq2.getOrDefault(word, 0);
            dotProduct += v1 * v2;
            norm1 += v1 * v1;
            norm2 += v2 * v2;
        }

        return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
    }


}
